%%%-------------------------------------------------------------------
%%% @author wukai
%%% @copyright (C) 2017, <COMPANY>
%%% @doc
%%%
%%% @end
%%% Created : 28. 十一月 2017 11:03
%%%-------------------------------------------------------------------
-module(mqtt_user).
-author("wukai").

-record(user, {username, password, time}).
%% API
-export([login/1, create_user_table/0, save/2]).

create_user_table() ->
  mnesia:create_table(user,
    [
      {storage_properties, [{dets, [{auto_save, 3000}]}]},
      {disc_copies, [node()]},
      {type, set},
      {attributes, record_info(fields, user)}
    ]
  ).

login({undefined, undefined}) -> false;
login({"admin", "admin"}) -> true;
login({"user", "user"}) -> true;
%%验证username是否存在
login({User, Pass}) ->
  F = fun() -> mnesia:read(user, User) end,
  R = mnesia:transaction(F),
  case R of
    {atomic, ResultOfFun} when is_list(ResultOfFun), length(ResultOfFun) > 0 ->
      [{U, P, _} | _] = ResultOfFun,
      if
        User == U, Pass == P -> true;
        true -> false
      end
    ;
    {aborted, Reason} -> log:log("login failed ~p", [Reason]), false
  end.

save(Username, Pass) ->
  User = #user{username = Username, password = Pass, time = time_utils:timestamp()},
  case mnesia:transaction(fun() -> mnesia:write(User) end) of
    {atomic, ok} -> ok;
    _ -> false
  end.
